<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="职位名称" prop="jobName">
        <el-input v-model="formData.jobName" placeholder="请输入职位名称" />
      </el-form-item>
      <el-form-item label="招聘类型" prop="jobType">
        <el-radio-group v-model="formData.jobType">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.JOB_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="岗位职责" prop="jobDuty">
        <el-input v-model="formData.jobDuty" type="textarea" placeholder="请输入岗位职责" />
      </el-form-item>
      <el-form-item label="岗位要求" prop="jobAsk">
        <el-input v-model="formData.jobAsk" type="textarea" placeholder="请输入岗位要求" />
      </el-form-item>
        <el-form-item label="薪资范围" prop="salaryRangeFrom">
          <el-select v-model="formData.salaryRangeFrom" placeholder="请输入最低薪资" :disabled="isSalaryMeet">
            <el-option  
            v-for="salary in salaryOptions1"
            :key="salary"
            :label="salary+'k'"
            :value="salary"/>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="salaryRangeTo">
          <el-select v-model="formData.salaryRangeTo" placeholder="请输入最高薪资" :disabled="isSalaryMeet">
            <el-option  
            v-for="salary in salaryOptions2"
            :key="salary"
            :label="salary+'k'"
            :value="salary"/>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="salaryMonth">
          <el-select v-model="formData.salaryMonth" :disabled="isSalaryMeet">
            <el-option  
            v-for="month in salaryMonthArray"
            :key="month"
            :label="month+'月'"
            :value="month"/>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="salaryMeet">
            <el-checkbox v-model="salaryMeetCheck" @change="handleSalaryMeetChange">薪资面议</el-checkbox>
        </el-form-item>
      <el-form-item label="工作地点" prop="jobCity">
        <!-- <el-select v-model="formData.jobCity" placeholder="请选择工作城市, 用’;‘隔开">
          <el-option label="请选择字典生成" value="" />
        </el-select> -->
        <el-cascader 
        v-model="formData.jobCity"
        :options="cityTree" 
        :props="optionProps" 
        :show-all-levels="false" 
        clearable />
      </el-form-item>
      <el-form-item label="学历要求" prop="jobRequireEdu">
        <el-select v-model="formData.jobRequireEdu">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.JOB_REQUIRE_EDU)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="简历投递截至时间" prop="jobEndDay">
        <el-date-picker
          v-model="formData.jobEndDay"
          type="date"
          value-format="x"
          placeholder="选择截至时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">发布</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { JobInfoApi, JobInfoVO } from '@/api/dbit/jobinfo'
import {format} from 'date-fns'

/** 企业职位信息 表单 */
defineOptions({ name: 'JobInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
let isSalaryMeet = ref(false) // 是否薪资面议
const salaryMonthArray = [12,13,14,15,16,17,18,19,20,21,22,23,24]
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const salaryMeetCheck = ref(false)

const formData = ref({
  jobName: undefined,
  jobType: undefined,
  jobDuty: undefined,
  jobAsk: undefined,
  salaryRangeFrom: undefined,
  salaryRangeTo: undefined,
  salaryMonth: undefined,
  salaryMeet: 1,
  jobCity: [],
  jobRequireEdu: undefined,
  jobEndDay: undefined,
})
const cityTree = ref([])
const salaryOptions1 = ref(Array.from({length: 250}, (_, i) => i + 1))
const salaryOptions2 = ref(Array.from({length: 260}, (_, i) => i + 2))
// 级联下拉配置
const optionProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  multiple: true
 }

/**表单提交规则 */
const formRules = reactive({
  jobName: [
    { required: true, message: '请输入职位名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  jobType: [{ required: true, message: '请选择招聘类型', trigger: 'change' }],
  jobDuty: [
    { required: true, message: '请输入岗位职责', trigger: 'blur'}
  ],
  jobAsk: [
    { required: true, message: '请输入岗位要求', trigger: 'blur'}
  ],
  salaryRangeFrom: [
    { required: true, message: '请输入最低薪资', trigger: 'change'}
  ],
  salaryRangeTo: [
    { required: true, message: '请输入最高薪资', trigger: 'change'}
  ],
  salaryMonth: [
    { required: true, message: '请选择薪资月份', trigger: 'change'}
  ],
  salaryMeet: [
    { required: true, message: '请选择薪资面议', trigger: 'change'}
  ],
  jobCity: [
    { required: true, message: '请选择工作地点', trigger: 'change'}
  ],
  jobRequireEdu: [
    { required: true, message: '请选择学历要求', trigger: 'change'}
  ],
  jobEndDay: [
    { required: true, message: '请选择简历投递截至时间', trigger: 'change'}
  ]
})
const formRef = ref() // 表单 Ref


/** 点击薪资面议 */
const handleSalaryMeetChange = (val: boolean) => {
  isSalaryMeet.value = val
  // isSalaryMeet.value ? formData.value.salaryMeet = 1 : formData.value.salaryMeet = 2
  // 重置表单中的最低薪资和最高薪资和月份
  formData.value.salaryRangeFrom = undefined
  formData.value.salaryRangeTo = undefined
  formData.value.salaryMonth = undefined
  // 修改最低薪资和最高薪资和月份的表单验证，改为不必填
  formRules.salaryRangeFrom.forEach((rule: any) => {
    rule.required = !val
  })
  formRules.salaryRangeTo.forEach((rule: any) => {
    rule.required = !val
  })
  formRules.salaryMonth.forEach((rule: any) => {
    rule.required = !val
  })
  
}
/** 获取城市列表 */
const getCityList = async () => {
  const c = await JobInfoApi.getCityTree()
  // 只获取城市和省份，县级去除
  c.forEach((item: any) => {
    if(item.children.length > 0){
      item.children.map((j: any) => {
        j.children = undefined
      })
    }
  })
  cityTree.value = c
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  getCityList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  isSalaryMeet.value = false
  salaryMeetCheck.value = false
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await JobInfoApi.getJobInfo(id)
      isSalaryMeet.value = formData.value.salaryMeet === 1 ? true : false
      /** 将checkBox选中 */
      salaryMeetCheck.value = formData.value.salaryMeet === 1 ? true : false
      if(salaryMeetCheck.value){
        handleSalaryMeetChange(true)
      }
      const arr = await JobInfoApi.showCascader(formData.value.jobCity)
      formData.value.jobCity = arr
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    isSalaryMeet.value ? formData.value.salaryMeet = 1 : formData.value.salaryMeet = 2
    const cityArr = []
    formData.value.jobCity.forEach((item: any) => cityArr.push(item[1]))
    formData.value.jobCity = cityArr.join(';')
    if(typeof formData.value.jobEndDay === 'number'){
      const futureDate = new Date();
      futureDate.setTime(formData.value.jobEndDay)
      formData.value.jobEndDay = futureDate
      // 使用date-fns格式化日期
      formData.value.jobEndDay = format(futureDate, 'yyyy-MM-dd')
    }
    const data = formData.value as unknown as JobInfoVO
    console.log(data)
    if (formType.value === 'create') {
      await JobInfoApi.createJobInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await JobInfoApi.updateJobInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    jobName: undefined,
    jobType: undefined,
    jobDuty: undefined,
    jobAsk: undefined,
    salaryRangeFrom: undefined,
    salaryRangeTo: undefined,
    salaryMonth: undefined,
    salaryMeet: 1,
    jobCity: [],
    jobRequireEdu: undefined,
    jobEndDay: undefined,
  }
  formRef.value?.resetFields()
}
</script>